package com.example.qincetest.lifecycle

import android.app.Activity
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager.FragmentLifecycleCallbacks
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import timber.log.Timber

class AppActivityLifecycleCallbacks:ActivityLifecycleCallbacks {
    private val clickEventHelper = ClickEventHelper()
    private val fragmentCallback = AppFragmentLifecycleCallbacks();

    override fun onActivityCreated(p0: Activity, p1: Bundle?) {
        Timber.d("$p0.javaClass.toString() onActivityCreated")
        val lifecycleScope = ((p0 as? LifecycleOwner)?.lifecycleScope) ?: return
        lifecycleScope.launchWhenCreated {//2
            clickEventHelper.bindAccessibilityDelegateToViews(p0)
        }

        if (p0 is FragmentActivity) {
            // 为每个Activity注册Fragment回调
            p0.supportFragmentManager.registerFragmentLifecycleCallbacks(fragmentCallback, true)
        }
    }

    override fun onActivityStarted(p0: Activity) {
        Timber.d("$p0.javaClass.toString() onActivityStarted")
    }

    override fun onActivityResumed(p0: Activity) {
        Timber.d("${p0.javaClass} onActivityResumed title=${p0.title}")
    }

    override fun onActivityPaused(p0: Activity) {
        Timber.d("$p0.javaClass.toString() onActivityPaused")
    }

    override fun onActivityStopped(p0: Activity) {
        Timber.d("$p0.javaClass.toString() onActivityStopped")
    }

    override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
        Timber.d("$p0.javaClass.toString() onActivitySaveInstanceState")
    }

    override fun onActivityDestroyed(p0: Activity) {
        Timber.d("$p0.javaClass.toString() onActivityDestroyed")
        if (p0 is FragmentActivity) {
            // 注销Fragment回调
            p0.supportFragmentManager.unregisterFragmentLifecycleCallbacks(fragmentCallback)
        }
    }
}